package com.ruoyi.web.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.domain.mes.MesCustom;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.service.IMesCustomService;
import com.ruoyi.web.service.SupplierCheckoutService;
import com.ruoyi.web.service.SupplierPersonService;
import com.ruoyi.web.service.SupplierService;
import com.ruoyi.web.vo.Supplier;
import com.ruoyi.web.vo.SupplierCheckout;
import com.ruoyi.web.vo.SupplierPerson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/supplier")
public class SupplierController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(IMesCustomService.class);
    @Resource
    private SupplierService supplierService;
    @Resource
    private SupplierPersonService supplierPersonService;
    @Resource
    private SupplierCheckoutService supplierCheckoutService;

    @Resource
    private MesConfigMapper configMapper;

    @PostMapping(value = "/list")
    public TableDataInfo list(@RequestBody Map<String, String> params) {
        startPage(params);
        String supplierCode = params.get("supplierCode");
        String name = params.get("name");
        String type = params.get("type");
        String status = params.get("status");
        return getDataTable(supplierService.list(new QueryWrapper<Supplier>().lambda()
                .like(StringUtils.isNotEmpty(supplierCode), Supplier::getSupplierCode, supplierCode)
                .like(StringUtils.isNotEmpty(name), Supplier::getName, name)
                .like(StringUtils.isNotEmpty(type), Supplier::getType, type)
                .eq(StringUtils.isNotEmpty(status), Supplier::getStatus, status)
                .orderByDesc(Supplier::getCreateTime)
        ));
    }

    @PostMapping(value = "/export")
    public void export(HttpServletResponse response, Supplier supplier) {
        String supplierCode = supplier.getSupplierCode();
        String name = supplier.getName();
        String type = supplier.getType();
        String status = supplier.getStatus();
        List<Supplier> list = supplierService.list(new QueryWrapper<Supplier>().lambda()
                .like(StringUtils.isNotEmpty(supplierCode), Supplier::getSupplierCode, supplierCode)
                .like(StringUtils.isNotEmpty(name), Supplier::getName, name)
                .like(StringUtils.isNotEmpty(type), Supplier::getType, type)
                .eq(StringUtils.isNotEmpty(status), Supplier::getStatus, status)
                .orderByDesc(Supplier::getCreateTime));
        ExcelUtil<Supplier> util = new ExcelUtil<>(Supplier.class);
        util.exportExcel(response, list, "供应商信息数据");
    }

    /**
     * 下载供应商信息模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Supplier> util = new ExcelUtil<Supplier>(Supplier.class);
        util.importTemplateExcel(response, "供应商信息数据");
    }

    /**
     * 导入供应商信息数据
     */
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<Supplier> util = new ExcelUtil<Supplier>(Supplier.class);
        List<Supplier> mesSupplierList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = importSupplier(mesSupplierList, updateSupport, operName);
        return success(message);
    }

    /**
     * 导入供应商信息数据
     *
     * @param mesSupplierList 供应商信息数据
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */

    public String importSupplier(List<Supplier> mesSupplierList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(mesSupplierList) || mesSupplierList.size() == 0) {
            throw new ServiceException("导入供应商信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        List<Supplier> SupplierList = new ArrayList<>();
        for (Supplier supplierMode : mesSupplierList) {
            try {
                // 验证是否存在这个供应商
                Supplier m = supplierService.getOne(new QueryWrapper<Supplier>().lambda()
                        .eq(StringUtils.isNotEmpty(supplierMode.getName()), Supplier::getName, supplierMode.getName())
                        .last("LIMIT 1"));
                if (StringUtils.isNull(m)) {
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(supplierMode.getPhone())) {
                        String tel = "^1[3|4|5|6|7|8|9][0-9]\\d{8}$"; // 手机号正则校验
                        if (!Pattern.matches(tel, supplierMode.getPhone())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、联系电话 " + supplierMode.getPhone() + " 有误");
                        }
                    }

                    if (org.apache.commons.lang3.StringUtils.isNotBlank(supplierMode.getUsci())) {
                        String tel = "^[0-9A-HJ-NPQRTUWXY]{2}\\d{6}[0-9A-HJ-NPQRTUWXY]{10}$"; // 统一社会信用代码正则校验
                        if (!Pattern.matches(tel, supplierMode.getUsci())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、统一社会信用代码 " + supplierMode.getUsci() + " 有误");
                        }
                    }

                    if (org.apache.commons.lang3.StringUtils.isNotBlank(supplierMode.getBankCode())) {
                        String tel = "^[0-9]{9,18}$"; // 银行账号正则校验
                        if (!Pattern.matches(tel, supplierMode.getBankCode())) {
                            failureNum++;
                            failureMsg.append("<br/>" + failureNum + "、银行账号 " + supplierMode.getBankCode() + " 有误");
                        }
                    }
                    supplierMode.setCreateTime(DateUtils.getNowDate());
                    supplierMode.setCreateBy(operName);
                    supplierMode.setStatus("0");
                    SupplierList.add(supplierMode);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、供应商信息 " + supplierMode.getName() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、供应商信息 " + supplierMode.getName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、供应商信息 " + supplierMode.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            supplierService.saveBatch(SupplierList);
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody Supplier supplier) {

        // 新增
        if (supplier.getPid() == null) {
            supplier.setPid(UUID.randomUUID().toString().replace("-", ""));

            // 生成编号
            Map<String, Object> map = new HashMap<>();
            map.put("columnName", "supplier_code");
            map.put("tableName", "mes_supplier");
            int maxNum = configMapper.getMouthMaxId(map);
            String code = PinYinUtils.getCodeNormal(maxNum, "GYS");

            supplier.setSupplierCode(code);//供应商编号
            supplier.setCreateTime(DateUtils.getNowDate());
            supplier.setCreateBy(SecurityUtils.getUsername());


            if (supplier.getSupplierPersonList() != null) {
                supplier.getSupplierPersonList().forEach(e -> {
                    e.setSupplierId(supplier.getPid());
                });
            }
            if (supplier.getSupplierCheckoutList() != null) {
                supplier.getSupplierCheckoutList().forEach(e -> {
                    e.setSupplierId(supplier.getPid());
                });
            }

        }
        // 修改
        else {
            supplier.setUpdateTime(DateUtils.getNowDate());
            supplier.setUpdateBy(SecurityUtils.getUsername());
        }
        supplierService.saveOrUpdate(supplier);
        if (supplier.getSupplierPersonList() != null) {
            supplierPersonService.remove(new QueryWrapper<SupplierPerson>().lambda().eq(SupplierPerson::getSupplierId, supplier.getPid()));
            supplierPersonService.saveBatch(supplier.getSupplierPersonList());
        }
        if (supplier.getSupplierCheckoutList() != null) {
            supplierCheckoutService.remove(new QueryWrapper<SupplierCheckout>().lambda().eq(SupplierCheckout::getSupplierId, supplier.getPid()));
            supplierCheckoutService.saveBatch(supplier.getSupplierCheckoutList());
        }
        return AjaxResult.success("添加成功", supplier.getPid());
    }

    @PostMapping(value = "/getById")
    public AjaxResult getById(@RequestBody Map<String, String> params) {
        String pid = params.get("pid");
        Supplier supplier = supplierService.getById(pid);
        List<SupplierPerson> supplierPersonList = supplierPersonService.list(new QueryWrapper<SupplierPerson>().lambda().eq(SupplierPerson::getSupplierId, supplier.getPid()));
        List<SupplierCheckout> supplierCheckoutList = supplierCheckoutService.list(new QueryWrapper<SupplierCheckout>().lambda().eq(SupplierCheckout::getSupplierId, supplier.getPid()));
        supplier.setSupplierPersonList(supplierPersonList);
        supplier.setSupplierCheckoutList(supplierCheckoutList);

        return AjaxResult.success("查询成功", supplier);
    }

    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        String id = params.get("pid");
        supplierService.removeById(id);
        supplierPersonService.remove(new QueryWrapper<SupplierPerson>().lambda().eq(SupplierPerson::getSupplierId, id));
        supplierCheckoutService.remove(new QueryWrapper<SupplierCheckout>().lambda().eq(SupplierCheckout::getSupplierId, id));
        return AjaxResult.success("删除成功");
    }
}
